import util from '../utils/util.js'

const convolute = function(canvas, pixels, weights) {
    var side = Math.round(Math.sqrt(weights.length));
    var halfSide = Math.floor(side/2);
    var src = pixels.data;
    var sw = pixels.width;
    var sh = pixels.height;
    // pad output by the convolution matrix
    var w = sw;
    var h = sh;
    let temporaryCtx = canvas.getContext('2d')
    var output = temporaryCtx.createImageData(w, h);
    var dst = output.data;
    // go through the destination image pixels
    for (var y=0; y<h; y++) {
        for (var x=0; x<w; x++) {
            var sy = y;
            var sx = x;
            var dstOff = (y*w+x)*4;
            // calculate the weighed sum of the source image pixels that
            // fall under the convolution matrix
            var r=0, g=0, b=0, a=0;
            for (var cy=0; cy<side; cy++) {
                for (var cx=0; cx<side; cx++) {
                    var scy = sy + cy - halfSide;
                    var scx = sx + cx - halfSide;
                    if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
                        var srcOff = (scy*sw+scx)*4;
                        var wt = weights[cy*side+cx];
                        r = util.minMax(r + src[srcOff] * wt, 0, 255);
                        g = util.minMax(g + src[srcOff+1] * wt, 0, 255);
                        b = util.minMax(b + src[srcOff+2] * wt, 0, 255);
                        a += src[srcOff+3] * wt;
                    }
                }
            }
            dst[dstOff] = util.minMax(r, 0 ,255);
            dst[dstOff+1] = util.minMax(g, 0 ,255);
            dst[dstOff+2] = util.minMax(b, 0 ,255);
            dst[dstOff+3] = 255;
        }
    }
    return output;
}

export default convolute;